package cn.edu.hunau.service.impl;

import cn.edu.hunau.common.BusinessException;
import cn.edu.hunau.common.ResultCodeEnum;
import cn.edu.hunau.mapper.UserMapper;
import cn.edu.hunau.pojo.User;
import cn.edu.hunau.request.LoginReq;
import cn.edu.hunau.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author hb
 * @date 2024-04-15 10:34:45
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Override
    @Transactional(readOnly = true)
    public User findById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void checkUserExistsByTelphone(String telphone) {
        User user = userMapper.selectByTelphone(telphone);
        if(user != null){
            //抛出业务异常
            throw new BusinessException(ResultCodeEnum.TELPHONE_EXISTS);
        }
    }

    @Override
    @Transactional
    public void regist(User user) {
        userMapper.insertSelective(user);
    }

    @Override
    @Transactional
    public User login(LoginReq loginData) {

       User user= userMapper.selectByTelphoneAndPassword(loginData.getTelphone(),loginData.getPassword());
       if(user==null){
         throw new BusinessException(ResultCodeEnum.LOGIN_FAIL);
       }
        return user;
    }
}
